import axios from 'axios';
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (prefix){
        return this.slice(0, prefix.length) === prefix;
    };
}
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (suffix){
        return this.slice(-1*suffix.length) === suffix;
    };
}
let serverName = function(){
  if(typeof process!='undefined'){
      if(process.env.NODE_ENV == 'development'){
        return "/youyaboot-admin";
      }
  }
  //发布场景智能分析path
  var href = window.location.href.replace("https://","").replace("http://","");
  var hrefArr = href.split("/");
  if(hrefArr[1]==='editor'){//特殊处理 本地开发的时候
      return "/youyaboot-admin/";
  }
  var pre = href.split("?")[0];
  if(pre.indexOf("/magicalcoder/")==-1){
      return "";
  }
  var arr = pre.split("/magicalcoder/");
  if(arr[0].indexOf("/")==-1){
    return "/";
  }
  var newArr = arr[0].split("/");
  newArr[0]="";
  var realPath = newArr.join("/");
  return realPath+"/";
}
let vueCtx = null;
var serverNameConst = serverName();
const service = axios.create({
//  baseURL: serverName(), //使用代理
  timeout: 15000
});

let openapiUrl = function(url){
    if(window['NODE_DEV']=='dev'){
      serverNameConst = "/youyaboot-admin";
    }
    if(!url){
        return url;
    }
    if(url.startsWith("magical_lowcode/")){
        url = (serverNameConst+"/"+url).replace("//magical_lowcode/","/magical_lowcode/");
    }else if(url.startsWith("/magical_lowcode/")){
        url = (serverNameConst+url).replace("//magical_lowcode/","/magical_lowcode/");
    }
    return url;
}
service.interceptors.request.use(
    config => {
        //magical_coder 低代码工具的通用接口
        config.url = openapiUrl(config.url);
        if(config.param){
            if(config.method=='get'){
                config.params = config.param;
            }else{
                config.data = config.param;
            }
        }
        //破除ie浏览器缓存
        if(config.url.indexOf("?")!=-1){
            config.url = config.url+"&_"+(new Date().getTime())
        }else{
            config.url = config.url+"?_"+(new Date().getTime())
        }
//        console.log(config.url)
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            var res = response.data;
            if(typeof res['code']!== 'undefined' && res.code===0){
                return res;
            }else{
                if(typeof res['desc']!='undefined' && res.desc){
                    vueCtx.$message({type:"error",message:res.desc,duration:5000});
                    return  Promise.reject();
                }
            }
            return res;
        } else {
            return Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);
let util = {
      //包裹工具的地址
      wrapMagicalOpenapiUrl:function(url){
          return openapiUrl(url)
      },
      //包裹服务名
      wrapServerName:function(url,wrap){
          if(!wrap || !url || url.startsWith("http") || url.startsWith("/")){
              return url;
          }
          if(url.startsWith(serverNameConst)){
              return url;
          }
          if(url.indexOf("?")!=-1){
              return serverNameConst+url+"&__mc";
          }
          return serverNameConst+url+"?__mc";
      },
      unwrapServerName:function(url,unwrap){
          if(unwrap && url.indexOf("__mc")!=-1){
              return url.split(serverNameConst)[1].replace("&__mc","").replace("?__mc","");
          }
          return url;
      },
      isMcQueryUrl:function (mcQueryUrl){
        if(mcQueryUrl) {
          var url = mcQueryUrl.split("?")[0];
          if (mcQueryUrl.indexOf("magical_lowcode/openapi/crud/") != -1 &&
            (url.indexOf("page") != -1 || url.indexOf("list")) != -1) {
            return true;
          }
        }
        return false;
      },
      paramsToJson:function(params){
          var json = []
          if(params && params.length>0){
              for(var i=0;i<params.length;i++){
                  var pItem = params[i];
                  var compare = pItem.compare;
                  var name = pItem.name;
                  var value = pItem.value;
                  var type = pItem.type;
                  if(name && value!==''){
                      if(type=='number' && !isNaN(value)){
                          json.push("\""+name+"\":"+value);
                      }else{
                        json.push("\""+name+"\":"+"\""+value+"\"");
                      }
                  }
              }
          }
          var param = JSON.parse("{"+json.join(",")+"}");
          return param;
      },
      paramsTomMcQuery:function(params){
          var param = {param:{},condition:{}}
          var json = []
          if(params && params.length>0){
              for(var i=0;i<params.length;i++){
                  var pItem = params[i];
                  var compare = pItem.compare;
                  var name = pItem.name;
                  var value = pItem.value;

                  var type = pItem.type;
                  if(name && value!==''){
                      if(type=='number' && !isNaN(value)){
                          json.push("\""+name+"\":"+value);
                      }else{
                        json.push("\""+name+"\":"+"\""+value+"\"");
                      }
                      param.condition[name]=compare;
                  }
              }
          }
          param.param = JSON.parse("{"+json.join(",")+"}");
          return param;
      }
}
const request = {axios:function(param){vueCtx = param.$vue;return service(param);},util:util}
export default request;
